
#include <disk.hpp>
#include <string.h>


int Disk::Attach(char *file)
{
	char *fname;
	char *ext;
	int guess[] = {0, 1, 2, 3, 4 };
	/* 0: physical disk
	 * 1: raw disk image
	 * 2: vhd image
	 * 3: vmdk image
	 * 4: vdi image
	 */
	DiskBase *trydisk;

	if(!file)
		return 0;
	
	fname = strrchr(file, '/');
	if(fname == NULL)
		fname = file;
	else
		fname ++;

	ext = strrchr(fname, '.');
	if(ext)	// with extension name
	{
		ext ++;
		if(strcasecmp(ext, "vhd") == 0)
		{
			guess[0] = 2;
			guess[2] = 0;
		}
		else if(strcasecmp(ext, "vmdk") == 0)
		{
			guess[0] = 3;
			guess[3] = 0;
		}
		else if(strcasecmp(ext, "vdi") == 0)
		{
			guess[0] = 4;
			guess[4] = 0;
		}
		else if(strcasecmp(ext, "img") == 0)
		{
			guess[0] = 1;
			guess[1] = 0;
		}
	}
		// without extension or extension unknown, try physical disk first
	for(int i = 0; i < 5; i ++)
	{
		switch(guess[i])
		{
		case 0:
			trydisk = new PhysicalDisk();
			break;
		case 1:
			trydisk = new RawDisk;
			break;
		case 2:
			trydisk = new VHDDisk;
			break;
		case 3:
			trydisk = new VMDKDisk;
			break;
		case 4:
			trydisk = new VDIDisk;
			break;
		}
			
		if(trydisk->Attach(file))
		{
			diskobject = trydisk;
			delete trydisk;
			return 1;
		}

		delete trydisk;
	}
		
	return 0;
}






